package com.mail.transfer.email.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xiaocg
 */
@Slf4j
public class MailNettyClient {

    private String host;
    private Integer port;


    public MailNettyClient(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //发送消息
            future.channel().writeAndFlush("你好啊");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("客户端连接失败:{}",e.getMessage());
        }finally {
            group.shutdownGracefully();
        }
    }
}
